package com.qdhh.enrollment.controller.miniapp;

import cn.dev33.satoken.stp.StpUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.qdhh.enrollment.common.Result;
import com.qdhh.enrollment.mapper.UserMapper;
import com.qdhh.enrollment.model.Student;
import com.qdhh.enrollment.model.User;
import com.qdhh.enrollment.service.StudentService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.time.LocalDateTime;

@Tag(name = "小程序-实名认证", description = "姓名+身份证实名认证接口，微信登录已迁移至 /api/miniapp/user/login")
@RestController
@RequestMapping("/api/miniapp/auth")
public class MiniappAuthController {

    private final UserMapper userMapper;
    private final StudentService studentService;

    public MiniappAuthController(UserMapper userMapper, StudentService studentService) {
        this.userMapper = userMapper;
        this.studentService = studentService;
    }

    @Operation(summary = "实名认证（姓名+身份证）")
    @PostMapping("/identityVerify")
    public Result<String> identityVerify(@RequestBody IdentityRequest body) {
        if (!StpUtil.isLogin()) {
            return Result.failure(401, "未登录");
        }
        String name = body != null ? body.getName() : null;
        String idCard = body != null ? body.getIdCard() : null;
        if (!StringUtils.hasText(name) || !StringUtils.hasText(idCard)) {
            return Result.failure(400, "姓名/身份证不能为空");
        }

        String loginId = StpUtil.getLoginIdAsString();
        User user = userMapper.selectById(loginId);
        if (user == null) {
            // 允许根据身份证匹配任意有效用户（无手机号绑定场景）
            user = userMapper.selectOne(new QueryWrapper<User>().eq("id_card", idCard).eq("status", 1).last("limit 1"));
        }
        if (user == null || !idCard.equals(user.getIdCard())) {
            return Result.failure(403, "认证失败：未找到匹配的用户");
        }

        // 标记已认证（直接设置，不再依赖 student_profiles 是否存在）
        StpUtil.getSession().set("identityVerified", 1);
        try {
            Student student = studentService.getById(loginId);
            if (student != null) {
                student.setIdentityVerified(1);
                student.setIdentityVerifiedAt(LocalDateTime.now());
                student.setIdentityVerifyMethod("manual");
                student.setIdentityVerifyRemark("姓名+身份证校验通过");
                studentService.updateById(student);
            }
        } catch (Exception ignored) {
        }

        return Result.success("OK", "VERIFIED");
    }

    public static class IdentityRequest {
        private String name;
        private String idCard;
        public String getName() { return name; }
        public void setName(String name) { this.name = name; }
        public String getIdCard() { return idCard; }
        public void setIdCard(String idCard) { this.idCard = idCard; }
    }
}


